
UBERQUEST_VERSION = "Reborn Again 3.0 CC"

--UIPanelWindows["UberQuest_List"] = {area = "left", pushable = 997}
BINDING_HEADER_UBERQUEST_SEP = "Uber Quest Reborn Again"
BINDING_NAME_UBERQUEST_CONFIG = BINDING_NAME_UBERQUEST_CONFIG
BINDING_NAME_UBERQUEST_CONFIG2 = BINDING_NAME_UBERQUEST_CONFIG2

UBERQUEST_QUESTS_DISPLAYED = 22
UBERQUEST_QUESTLINE_HEIGHT = 16

UBERQUEST_NUM_MINION_LINES = 60

UberQuest_Player = nil --global
UberQuest_Minion_ColorPicker = { r = 1, g = 1, b = 1 } -- global
local UberQuest_Config_Loaded = nil
local UberQuest_ThereAreQuests = nil
local UberQuest_MinionSetOnce = nil
local UberQuest_QuestTitles = nil
local UberQuest_SelectedQuest = nil
local UberQuest_ActivityTracker = {}
local UberQuest_GotFullList = nil
local UberQuest_DelayedConfigInit = nil
local UberQuest_InfoRequested = {}
local UberQuest_WatchTextIndex = 1
local UberQuest_LightHeadedSupport = false
local UberQuest_LightHeadedHooked = false

UberQuestDetails = {
	name = "UberQuest",
	version = UBERQUEST_VERSION,
	releaseDate = "2007.05.31",
	author = "Saien (Modded by BanMan and Ithilyn, Additions by CaptCrunch)",
	email = "Woosleyt@gmail.com",
	website = "http://ui.worldofwar.net/",
	category = MYADDONS_CATEGORY_QUESTS
}



function UberQuest_Minion_Reset()
	UberQuest_Minion:ClearAllPoints()
	UberQuest_Minion:SetPoint("CENTER","UIParent","CENTER",0,0)
	if (not UberQuest_Minion:IsVisible()) then
		UberQuest_MinionShowHide()
	end
end

local function UberQuest_Items_Update(questState)
	local isQuestLog = 0
	if (questState == "UberQuest_Details_ScrollChild_") then -- that's one change
		isQuestLog = 1
	end
	local numQuestRewards
	local numQuestChoices
	local numQuestSpellRewards = 0
	local money
	local spacerFrame
	if (isQuestLog == 1) then
		numQuestRewards = GetNumQuestLogRewards()
		numQuestChoices = GetNumQuestLogChoices()
		if ( GetQuestLogRewardSpell() ) then
			numQuestSpellRewards = 1
		end
		money = GetQuestLogRewardMoney()
		spacerFrame = UberQuest_Details_ScrollChild_SpacerFrame -- that's two!
		-- All this crap copied for TWO changes.
	else
		numQuestRewards = GetNumQuestRewards()
		numQuestChoices = GetNumQuestChoices()
		if ( GetRewardSpell() ) then
			numQuestSpellRewards = 1
		end
		money = GetRewardMoney()
		spacerFrame = QuestSpacerFrame
	end

	local totalRewards = numQuestRewards + numQuestChoices + numQuestSpellRewards
	local questItemName = questState.."Item"
	local material = QuestFrame_GetMaterial()
	local  questItemReceiveText = getglobal(questState.."ItemReceiveText")
	if (totalRewards == 0 and money == 0) then
		getglobal(questState.."RewardTitleText"):Hide()
	else
		getglobal(questState.."RewardTitleText"):Show()
		QuestFrame_SetTitleTextColor(getglobal(questState.."RewardTitleText"), material)
		QuestFrame_SetAsLastShown(getglobal(questState.."RewardTitleText"), spacerFrame)
	end
	if (money == 0) then
		getglobal(questState.."MoneyFrame"):Hide()
	else
		getglobal(questState.."MoneyFrame"):Show()
		QuestFrame_SetAsLastShown(getglobal(questState.."MoneyFrame"), spacerFrame)
		MoneyFrame_Update(questState.."MoneyFrame", money)
	end
	
	for i=totalRewards + 1, MAX_NUM_ITEMS, 1 do
		getglobal(questItemName..i):Hide()
	end
	local questItem, name, texture, quality, isUsable, numItems = 1
	if ( numQuestChoices > 0 ) then
		getglobal(questState.."ItemChooseText"):Show()
		QuestFrame_SetTextColor(getglobal(questState.."ItemChooseText"), material)
		QuestFrame_SetAsLastShown(getglobal(questState.."ItemChooseText"), spacerFrame)
		for i=1, numQuestChoices, 1 do	
			questItem = getglobal(questItemName..i)
			questItem.type = "choice"
			numItems = 1
			if ( isQuestLog == 1 ) then
				name, texture, numItems, quality, isUsable = GetQuestLogChoiceInfo(i)
			else
				name, texture, numItems, quality, isUsable = GetQuestItemInfo(questItem.type, i)
			end
			questItem:SetID(i)
			questItem:Show()
			-- For the tooltip
			questItem.rewardType = "item"
			QuestFrame_SetAsLastShown(questItem, spacerFrame)
			getglobal(questItemName..i.."Name"):SetText(name)
			SetItemButtonCount(questItem, numItems)
			SetItemButtonTexture(questItem, texture)
			if ( isUsable ) then
				SetItemButtonTextureVertexColor(questItem, 1.0, 1.0, 1.0)
				SetItemButtonNameFrameVertexColor(questItem, 1.0, 1.0, 1.0)
			else
				SetItemButtonTextureVertexColor(questItem, 0.9, 0, 0)
				SetItemButtonNameFrameVertexColor(questItem, 0.9, 0, 0)
			end
			if ( i > 1 ) then
				if ( math.fmod(i,2) == 1 ) then
					questItem:SetPoint("TOPLEFT", questItemName..(i - 2), "BOTTOMLEFT", 0, -2)
				else
					questItem:SetPoint("TOPLEFT", questItemName..(i - 1), "TOPRIGHT", 1, 0)
				end
			else
				questItem:SetPoint("TOPLEFT", questState.."ItemChooseText", "BOTTOMLEFT", -3, -5)
			end
			
		end
	else
		getglobal(questState.."ItemChooseText"):Hide()
	end
	local rewardsCount = 0
	if ( numQuestRewards > 0 or money > 0 or numQuestSpellRewards > 0) then
		QuestFrame_SetTextColor(questItemReceiveText, material)
		-- Anchor the reward text differently if there are choosable rewards
		if ( numQuestChoices > 0  ) then
			questItemReceiveText:SetText(TEXT(REWARD_ITEMS))
			local index = numQuestChoices
			if ( math.fmod(index, 2) == 0 ) then
				index = index - 1
			end
			questItemReceiveText:SetPoint("TOPLEFT", questItemName..index, "BOTTOMLEFT", 3, -5)
		else 
			questItemReceiveText:SetText(TEXT(REWARD_ITEMS_ONLY))
			questItemReceiveText:SetPoint("TOPLEFT", questState.."RewardTitleText", "BOTTOMLEFT", 3, -5)
		end
		questItemReceiveText:Show()
		QuestFrame_SetAsLastShown(questItemReceiveText, spacerFrame)
		-- Setup mandatory rewards
		for i=1, numQuestRewards, 1 do
			questItem = getglobal(questItemName..(i + numQuestChoices))
			questItem.type = "reward"
			numItems = 1
			if ( isQuestLog == 1 ) then
				name, texture, numItems, quality, isUsable = GetQuestLogRewardInfo(i)
			else
				name, texture, numItems, quality, isUsable = GetQuestItemInfo(questItem.type, i)
			end
			questItem:SetID(i)
			questItem:Show()
			-- For the tooltip
			questItem.rewardType = "item"
			QuestFrame_SetAsLastShown(questItem, spacerFrame)
			getglobal(questItemName..(i + numQuestChoices).."Name"):SetText(name)
			SetItemButtonCount(questItem, numItems)
			SetItemButtonTexture(questItem, texture)
			if ( isUsable ) then
				SetItemButtonTextureVertexColor(questItem, 1.0, 1.0, 1.0)
				SetItemButtonNameFrameVertexColor(questItem, 1.0, 1.0, 1.0)
			else
				SetItemButtonTextureVertexColor(questItem, 0.5, 0, 0)
				SetItemButtonNameFrameVertexColor(questItem, 1.0, 0, 0)
			end
			
			if ( i > 1 ) then
				if ( math.fmod(i,2) == 1 ) then
					questItem:SetPoint("TOPLEFT", questItemName..((i + numQuestChoices) - 2), "BOTTOMLEFT", 0, -2)
				else
					questItem:SetPoint("TOPLEFT", questItemName..((i + numQuestChoices) - 1), "TOPRIGHT", 1, 0)
				end
			else
				questItem:SetPoint("TOPLEFT", questState.."ItemReceiveText", "BOTTOMLEFT", -3, -5)
			end
			rewardsCount = rewardsCount + 1
		end
		-- Setup spell reward
		if ( numQuestSpellRewards > 0 ) then
			if ( isQuestLog == 1 ) then
				texture, name = GetQuestLogRewardSpell()
			else
				texture, name = GetRewardSpell()
			end
			questItem = getglobal(questItemName..(rewardsCount + numQuestChoices + 1))
			questItem:Show()
			-- For the tooltip
			questItem.rewardType = "spell"
			SetItemButtonCount(questItem, 0)
			SetItemButtonTexture(questItem, texture)
			getglobal(questItemName..(rewardsCount + numQuestChoices + 1).."Name"):SetText(name)
			if ( rewardsCount > 0 ) then
				if ( math.fmod(rewardsCount,2) == 0 ) then
					questItem:SetPoint("TOPLEFT", questItemName..((rewardsCount + numQuestChoices) - 1), "BOTTOMLEFT", 0, -2)
				else
					questItem:SetPoint("TOPLEFT", questItemName..((rewardsCount + numQuestChoices)), "TOPRIGHT", 1, 0)
				end
			else
				questItem:SetPoint("TOPLEFT", questState.."ItemReceiveText", "BOTTOMLEFT", -3, -5)
			end
		end
	else	
		questItemReceiveText:Hide()
	end
	if ( questState == "QuestReward" ) then
		QuestFrameCompleteQuestButton:Enable()
		QuestFrameRewardPanel.itemChoice = 0
		QuestRewardItemHighlight:Hide()
	end
end

local function UberQuest_Details_Update()
	local questID = GetQuestLogSelection()
	local questTitle = GetQuestLogTitle(questID)
	if ( not questTitle ) then
		questTitle = ""
	end
	if ( IsCurrentQuestFailed() ) then
		questTitle = questTitle.." - ("..TEXT(FAILED)..")"
	end
	UberQuest_Details_ScrollChild_QuestTitle:SetText(questTitle)

	local questDescription
	local questObjectives
	questDescription, questObjectives = GetQuestLogQuestText()
	UberQuest_Details_ScrollChild_ObjectivesText:SetText(questObjectives)
	
	local questTimer = GetQuestLogTimeLeft()
	if ( questTimer ) then
		UberQuest_Details.hasTimer = 1
		UberQuest_Details.timePassed = 0
		UberQuest_Details_ScrollChild_TimerText:Show()
		UberQuest_Details_ScrollChild_TimerText:SetText(TEXT(TIME_REMAINING).." "..SecondsToTime(questTimer))
		UberQuest_Details_ScrollChild_Objective1:SetPoint("TOPLEFT", "UberQuest_Details_ScrollChild_TimerText", "BOTTOMLEFT", 0, -10)
	else
		UberQuest_Details.hasTimer = nil
		UberQuest_Details_ScrollChild_TimerText:Hide()
		UberQuest_Details_ScrollChild_Objective1:SetPoint("TOPLEFT", "UberQuest_Details_ScrollChild_ObjectivesText", "BOTTOMLEFT", 0, -10)
	end
	
	local numObjectives = GetNumQuestLeaderBoards()
	for i=1, numObjectives, 1 do
		local string = getglobal("UberQuest_Details_ScrollChild_Objective"..i)
		local text
		local type
		local finished
		text, type, finished = GetQuestLogLeaderBoard(i)
		if ( not text or strlen(text) == 0 ) then
			text = type
		end
		if ( finished ) then
			string:SetTextColor(0.2, 0.2, 0.2)
			text = text.." ("..TEXT(COMPLETE)..")"
		else
			string:SetTextColor(0, 0, 0)
		end
		string:SetText(text)
		string:Show()
		QuestFrame_SetAsLastShown(string,UberQuest_Details_ScrollChild_SpacerFrame)
	end

	for i=numObjectives + 1, MAX_OBJECTIVES, 1 do
		getglobal("UberQuest_Details_ScrollChild_Objective"..i):Hide()
	end
	
	-- If there's money required then anchor and display it
	if ( GetQuestLogRequiredMoney() > 0 ) then
		if ( numObjectives > 0 ) then
			UberQuest_Details_ScrollChild_RequiredMoneyText:SetPoint("TOPLEFT", "UberQuest_Details_ScrollChild_Objective"..numObjectives, "BOTTOMLEFT", 0, -4)
		else
			UberQuest_Details_ScrollChild_RequiredMoneyText:SetPoint("TOPLEFT", "UberQuest_Details_ScrollChild_ObjectivesText", "BOTTOMLEFT", 0, -10)
		end
		
		MoneyFrame_Update("UberQuest_Details_ScrollChild_RequiredMoneyFrame", GetQuestLogRequiredMoney())
		
		if ( GetQuestLogRequiredMoney() > GetMoney() ) then
			-- Not enough money
			UberQuest_Details_ScrollChild_RequiredMoneyText:SetTextColor(0, 0, 0)
			-- quicksylver 8/20/08 - reconfigured color changes for "red"
			SetMoneyFrameColor("UberQuest_Details_ScrollChild_RequiredMoneyFrame", "red")
		else
			UberQuest_Details_ScrollChild_RequiredMoneyText:SetTextColor(0.2, 0.2, 0.2)
			-- quicksylver 8/20/08 - reconfigured color changes for "white"
			SetMoneyFrameColor("UberQuest_Details_ScrollChild_RequiredMoneyFrame", "white")
		end
		UberQuest_Details_ScrollChild_RequiredMoneyText:Show()
		UberQuest_Details_ScrollChild_RequiredMoneyFrame:Show()
	else
		UberQuest_Details_ScrollChild_RequiredMoneyText:Hide()
		UberQuest_Details_ScrollChild_RequiredMoneyFrame:Hide()
	end

	if ( GetQuestLogRequiredMoney() > 0 ) then
		UberQuest_Details_ScrollChild_DescriptionTitle:SetPoint("TOPLEFT", "UberQuest_Details_ScrollChild_RequiredMoneyText", "BOTTOMLEFT", 0, -10)
	elseif ( numObjectives > 0 ) then
		UberQuest_Details_ScrollChild_DescriptionTitle:SetPoint("TOPLEFT", "UberQuest_Details_ScrollChild_Objective"..numObjectives, "BOTTOMLEFT", 0, -10)
	else
		if ( questTimer ) then
			UberQuest_Details_ScrollChild_DescriptionTitle:SetPoint("TOPLEFT", "UberQuest_Details_ScrollChild_TimerText", "BOTTOMLEFT", 0, -10)
		else
			UberQuest_Details_ScrollChild_DescriptionTitle:SetPoint("TOPLEFT", "UberQuest_Details_ScrollChild_ObjectivesText", "BOTTOMLEFT", 0, -10)
		end
	end
	if ( questDescription ) then
		UberQuest_Details_ScrollChild_QuestDescription:SetText(questDescription)
		 QuestFrame_SetAsLastShown(UberQuest_Details_ScrollChild_QuestDescription,UberQuest_Details_ScrollChild_SpacerFrame)
	end
	local numRewards = GetNumQuestLogRewards()
	local numChoices = GetNumQuestLogChoices()
	local money = GetQuestLogRewardMoney()

	if ( (numRewards + numChoices + money) > 0 ) then
		UberQuest_Details_ScrollChild_RewardTitleText:Show()
		QuestFrame_SetAsLastShown(UberQuest_Details_ScrollChild_RewardTitleText,UberQuest_Details_ScrollChild_SpacerFrame)
	else
		UberQuest_Details_ScrollChild_RewardTitleText:Hide()
	end

	UberQuest_Items_Update("UberQuest_Details_ScrollChild_")
	UberQuest_Details_ScrollScrollBar:SetValue(0)
	UberQuest_Details_Scroll:UpdateScrollChildRect()
end

function UberQuest_List_OnShow()

	if (UberQuest_Config[UberQuest_Player].ListLocation == nil) then
--	if (true) then
		UberQuest_List_SaveLocation()
	else
		UberQuest_List_LoadLocation()
	end
	UberQuest_List:Show()
end


function UberQuest_List_SaveLocation()
	local point,relativeTo,relativePoint,xOff,yOff

	point,relativeTo,relativePoint,xOff,yOff = UberQuest_List:GetPoint();
	UberQuest_Config[UberQuest_Player].ListLocation = {}
	UberQuest_Config[UberQuest_Player].ListLocation.Point = point
	if (relativeTo == nil) then
		UberQuest_Config[UberQuest_Player].ListLocation.RelativeTo = ""
	else
		UberQuest_Config[UberQuest_Player].ListLocation.RelativeTo = relativeTo:GetName()
	end
	UberQuest_Config[UberQuest_Player].ListLocation.RelativePoint = relativePoint;
	UberQuest_Config[UberQuest_Player].ListLocation.XOff = xOff;
	UberQuest_Config[UberQuest_Player].ListLocation.YOff = yOff;
end

function UberQuest_List_LoadLocation()
	local point,relativeTo,relativePoint,xOff,yOff

	point = UberQuest_Config[UberQuest_Player].ListLocation.Point
	relativeTo = UberQuest_Config[UberQuest_Player].ListLocation.RelativeTo
	if (relativeTo == "") then
		relativeTo=nil
	end
	relativePoint = UberQuest_Config[UberQuest_Player].ListLocation.RelativePoint
	xOff = UberQuest_Config[UberQuest_Player].ListLocation.XOff
	yOff = UberQuest_Config[UberQuest_Player].ListLocation.YOff
	UberQuest_List:ClearAllPoints();
	UberQuest_List:SetPoint(point,relativeTo,relativePoint,xOff,yOff)
end

local function UberQuest_List_SetSelection(questID)
	local selectedQuest
	if ( questID == 0 ) then
		UberQuest_Details_Scroll:Hide()
		return
	end
	UberQuest_Details_Scroll:Show()

	-- Get xml id
	local id = questID - FauxScrollFrame_GetOffset(UberQuest_List_Scroll)
	
	UberQuest_SelectedQuest = questID
	SelectQuestLogEntry(questID)
	local titleButton = getglobal("UberQuest_List_Title"..id)
	local titleButtonTag = getglobal("UberQuest_List_Title"..id.."Tag")
	local questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isDaily = GetQuestLogTitle(questID)
	if ( isHeader ) then
		if ( isCollapsed ) then
			ExpandQuestHeader(questID)
                        UberQuest_Config[UberQuest_Player].expanded[questLogTitleText] = true
			return
		else
			-- 10/4/2007 by Oggy
			-- When the shift key is down, select or deselect all
			-- quests under this header
			if (IsShiftKeyDown()) then
				if (UberQuest_IsAllZoneQuestsChecked(questID)) then
					UberQuest_ToggleAllZoneQuests(questID,false)
				else
					UberQuest_ToggleAllZoneQuests(questID,true)
				end
			else
				CollapseQuestHeader(questID)
	                        UberQuest_Config[UberQuest_Player].expanded[questLogTitleText] = false
                        end
			return
		end
	else
		-- Set newly selected quest and highlight it
		UberQuest_List.selectedButtonID = questID
		local scrollFrameOffset = FauxScrollFrame_GetOffset(UberQuest_List_Scroll)
		if ( questID > scrollFrameOffset and questID <= (scrollFrameOffset + UBERQUEST_QUESTS_DISPLAYED) and questID <= GetNumQuestLogEntries() ) then
			titleButton:LockHighlight()
			titleButtonTag:SetTextColor(HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b)
			UberQuest_List_HighlightFrame_SkillHighlight:SetVertexColor(titleButton.r, titleButton.g, titleButton.b)
			UberQuest_List_HighlightFrame:SetPoint("TOPLEFT", "UberQuest_List_Title"..id, "TOPLEFT", 5, 0)
			UberQuest_List_HighlightFrame:Show()
		end
	end
	if ( GetQuestLogSelection() > GetNumQuestLogEntries() ) then
		return
	end
	UberQuest_Details_Title:SetText ("Uber Quest ("..UBERQUEST_VERSION..")")
	UberQuest_Details:Show()
	UberQuest_Details_Update()
end

-- 10/4/2007 by Oggy
-- Sets all quests underneath the given header id
-- to either be shown or hidden

function UberQuest_ToggleAllZoneQuests(headerID,Show)
	local myQuestID = headerID + 1
	local questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isDaily
	
	while (myQuestID <= GetNumQuestLogEntries()) do
		questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isDaily = GetQuestLogTitle(myQuestID)
		if (isHeader) then break end
		if (Show) then
			UberQuest_Config[UberQuest_Player].selected[questLogTitleText] = 1
		else
			UberQuest_Config[UberQuest_Player].selected[questLogTitleText] = nil
		end
		myQuestID = myQuestID + 1
	
	end
	UberQuest_List_Update()
	UberQuest_Minion_Update()
end

-- 2/4/2008 by Oggy
-- Selects or unselects a quest 

function UberQuest_ToggleQuest(questID,Show)
	local questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isDaily
	
	questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isDaily = GetQuestLogTitle(questID)
	--DEFAULT_CHAT_FRAME:AddMessage("In UberQuest_ToggleQuest text="..questLogTitleText)
	
		if (Show) then
			UberQuest_Config[UberQuest_Player].selected[questLogTitleText] = 1
		else
			UberQuest_Config[UberQuest_Player].selected[questLogTitleText] = nil
		end
		UberQuest_List_Update()
		UberQuest_Minion_Update()
end

-- 10/4/2007 by Oggy
-- Tests to see whether or not all quests underneath
-- the given header are checked.  If they are, then
-- true is returned.  If any of them aren't checked,
-- false is returned.

function UberQuest_IsAllZoneQuestsChecked(headerID)
	local myQuestID = headerID + 1
	local questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isDaily
	
	while (myQuestID <= GetNumQuestLogEntries()) do
		questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isDaily = GetQuestLogTitle(myQuestID)
		if (isHeader) then break end
		if (UberQuest_Config[UberQuest_Player].selected[questLogTitleText] == nil) then
			return (false)
		end
		myQuestID = myQuestID + 1	
	end
	return (true)
end

function UberQuest_MinionSelect_ShowHide(id,Show)
	local CheckIt
	if (Show == nil) then
		CheckIt = false
	else
		CheckIt=Show
	end
	if (UberQuest_QuestTitles[self:GetParent():GetID()]) then
		if (Show) then
			UberQuest_Config[UberQuest_Player].selected[UberQuest_QuestTitles[self:GetParent():GetID()]] = 1
		else
			UberQuest_Config[UberQuest_Player].selected[UberQuest_QuestTitles[self:GetParent():GetID()]] = nil
		end
		if (UberQuest_Minion:IsVisible()) then
			UberQuest_Minion_Update()
		end
	end
end


local function UberQuest_SetFirstValidSelection()
	-- Intentionally left at QuestLog_
	local selectableQuest = QuestLog_GetFirstSelectableQuest()
	UberQuest_List_SetSelection(selectableQuest)
end


local function UberQuest_ConfigInit()
	local config
	--DEFAULT_CHAT_FRAME:AddMessage("In UberQuest_ConfigInit")
	UberQuest_Config_Loaded = 1	
	if (not UberQuest_Config) then 
		UberQuest_Config = {}
		UberQuest_Config.showquestlevels = 1
		UberQuest_Config.useminion = 1
		UberQuest_Config.addnewquests = 1
		UberQuest_Config.addprogress = 1
	end
	if (not UberQuest_Config[UberQuest_Player]) then
		UberQuest_Config[UberQuest_Player] = {}
	end
	config = UberQuest_Config[UberQuest_Player]
	if (not config.selected) then
		config.selected = {}
	end
	if (not config.expanded) then
		config.expanded = {}
	end
	if (not config.alerted) then
		config.alerted = {}
	end
	if (not config.scale) then
		config.scale = 1
	end
	

	UberQuest_Config.speedquest = nil
	if (UberQuest_Config.useminion) then
		--DEFAULT_CHAT_FRAME:AddMessage("Minion in use, doing minion stuff")

		if (config.minionvisible) then
			--DEFAULT_CHAT_FRAME:AddMessage("Minion should be shown")
			if (not UberQuest_Minion:IsVisible()) then
				--DEFAULT_CHAT_FRAME:AddMessage("Minion isn't visible, showing it")
				UberQuest_MinionShowHide()
			end
		end
		--if (config.lockminion) then
		--	UberQuest_Minion_Move:Hide()
		--else
			UberQuest_Minion_Move:Show()
		--end
		if (UberQuest_Config.color and UberQuest_Config.color.r and UberQuest_Config.color.g and UberQuest_Config.color.b and UberQuest_Config.color.opacity) then
			UberQuest_MinionBackdrop:SetBackdropColor(UberQuest_Config.color.r, UberQuest_Config.color.g, UberQuest_Config.color.b)
			local alpha = 1.0 - UberQuest_Config.color.opacity
			UberQuest_MinionBackdrop:SetAlpha(alpha)
		else
			UberQuest_MinionBackdrop:SetBackdropColor(TOOLTIP_DEFAULT_BACKGROUND_COLOR.r, TOOLTIP_DEFAULT_BACKGROUND_COLOR.g, TOOLTIP_DEFAULT_BACKGROUND_COLOR.b)
			UberQuest_MinionBackdrop:SetAlpha(1)
		end
		if (config.lock and
			config.lock.corner and
			config.lock.pointone and
			config.lock.pointtwo) then
			UberQuest_Minion:ClearAllPoints()
			UberQuest_Minion:SetPoint(config.lock.corner,"UIParent","BOTTOMLEFT",config.lock.pointone,config.lock.pointtwo)
		end

		--  Load Scale settings
		
		scale = config.scale
		--DEFAULT_CHAT_FRAME:AddMessage ("ConfigInit:  scale is "..scale)
		UberQuest_Minion:SetScale(UIParent:GetScale() * scale)
		UberMinionScale:SetValue(scale * 100)

	end
	UberQuest_List_ConfigButton:Enable()
	UberQuest_List_SummonMinion:Enable()

        UberQuest_ExpandQuestZones()
end

function UberQuest_ExpandQuestZones()
   -- dunno why, but all quests seem collapsed >= 2.0.3.
   -- Remember which ones the player's opened and re-open them on load.
   local i = 1
   while true do
      local quest, level, questTag, suggestedGroup, isHeader, isCollapsed, isDaily = GetQuestLogTitle(i)
      if (not quest) then
         break
      end
      if (isHeader) then
         if (isCollapsed and UberQuest_Config[UberQuest_Player].expanded[quest]) then
            ExpandQuestHeader(i)
         elseif (not isCollapsed and not UberQuest_Config[UberQuest_Player].expanded[quest]) then
            CollapseQuestHeader(i)
         end
      end
      i = i + 1
   end
end

function UberQuest_DelayedConfigInit_OnUpdate(self, elapsed)
	if (UberQuest_DelayedConfigInit) then
		UberQuest_DelayedConfigInit = UberQuest_DelayedConfigInit - elapsed
		if (UberQuest_DelayedConfigInit < 0) then
			UberQuest_ConfigInit()
			UberQuest_DelayedConfigInit = nil
			UberQuest:Hide()
		end
	else -- Stop receiving OnUpdates
		UberQuest:Hide()
	end
end

function UberQuest_OnLoad(self)
	self:RegisterEvent("PLAYER_ENTERING_WORLD") 
	self:RegisterEvent("QUEST_LOG_UPDATE")
	self:RegisterEvent("PARTY_MEMBERS_CHANGED")
	self:RegisterEvent("ADDON_LOADED")
	self:RegisterEvent("PLAYER_LOGIN")
	self:RegisterEvent("QUEST_WATCH_UPDATE")
	self:RegisterEvent("UPDATE_FACTION")
	self:RegisterEvent("UNIT_QUEST_LOG_CHANGED")
	self:RegisterEvent("PARTY_MEMBER_ENABLE");
	self:RegisterEvent("PARTY_MEMBER_DISABLE");
	
	
	--Orig_GameTooltipOnShow = GameTooltip:GetScript("OnShow");
	GameTooltip:SetScript("OnShow",UberQuest_Tooltip_OnShow);
	
	DEFAULT_CHAT_FRAME:AddMessage("UberQuest ("..UBERQUEST_VERSION..") loaded.")
	
	QuestLogFrame:UnregisterAllEvents();
	QuestLog_OnShow = UberQuest_ListShowHide;
	
	local playerName = UnitName("player")
	if (playerName ~= UKNOWNBEING and playerName ~= UNKNOWNOBJECT) then
		UberQuest_Player = playerName
	end
end

function UberQuest_Tooltip_OnShow()
	UberQuest_ScanToolTip()
	if (Orig_GameTooltipOnShow) then
		Orig_GameTooltipOnShow()
	end
end

function UberQuest_OnEvent(self, event, ...)
	local arg1 = ...
	if (event == "ADDON_LOADED") then
           if (myAddOnsFrame_Register) then
              myAddOnsFrame_Register(UberQuestDetails)
           end

        elseif (event == "PLAYER_LOGIN") then
           -- Triggered immediately before PLAYER_ENTERING_WORLD on login and UI Reload, 
           -- but NOT when entering/leaving instances
           if (LightHeaded) then
              if (LightHeaded.DetachFrame) then
                 UberQuest_LightHeadedSupport = true
              else
                 DEFAULT_CHAT_FRAME:AddMessage("UberQuest: Upgrade your LightHeaded to a newer version and I can support it.")
              end
           end

        elseif (event == "PLAYER_ENTERING_WORLD") then
                if (UberQuest_Player) then
                        if (not UberQuest_Config_Loaded) then
                           UberQuest_DelayedConfigInit = 1 --10
                           UberQuest:Show()
                        else
                           UberQuest_ExpandQuestZones()
                        end
		end
		if (UberQuest_LightHeadedSupport) then
			-- Have to do this on PLAYER_ENTERING_WORLD, since otherwise the LightHeaded.db isn't ready yet.
			-- Note this event fires on every zone-in, so check if we've already done it first.
			--if (LightHeadedFrame:GetParent() ~= UberQuest_Details) then
			if (not UberQuest_LightHeadedHooked) then
				 UberQuest_LightHeadedHooked = true
				 DEFAULT_CHAT_FRAME:AddMessage("UberQuest: adding LightHeaded support.")
				 LightHeaded:AttachFrame()
				 LightHeaded:DetachFrame()
				 LightHeadedFrame:ClearAllPoints()
				 LightHeadedFrame:SetParent(UIParent)
				 LightHeadedFrame:SetHeight(424)
				 LightHeadedFrame:SetPoint("LEFT", UberQuest_Details, "RIGHT", -35, 24)
				 --LightHeadedFrame:SetPoint("TOPLEFT", UberQuest_List,"TOPRIGHT")
				 LightHeadedFrame:SetFrameStrata("HIGH")
				 LightHeadedFrame:Hide()
				 --LightHeaded:LoadQIDData(nil)
			end
		else
			getglobal("UberQuest_LHAttachButton"):Hide()
		end

	elseif (UberQuest_Config_Loaded and event == "QUEST_LOG_UPDATE") then
		UberQuest_List_Update()
		if (UberQuest_Details:IsVisible()) then
			UberQuest_Details_Update()
		end
		if (UberQuest_Minion:IsVisible() and UberQuest_Config[UberQuest_Player].selected) then
			UberQuest_Minion_Update()
                end
                CompletedQuestAlert()
                     
	elseif ( event == "PARTY_MEMBERS_CHANGED" ) then
		-- Pushable == Sharable. Blizzard likes things straight forward
		-- quicksylver 8/20/08 - Added "or GetRealNumRaidMembers() > 1 ) ) then"
		if ( GetQuestLogPushable() and ( GetRealNumPartyMembers() > 0 or GetRealNumRaidMembers() > 1 ) ) then
			UberQuest_List_ShareButton:Enable()
		else
			UberQuest_List_ShareButton:Disable()
		end
	elseif ( event == "UPDATE_MOUSEOVER_UNIT" ) then
		UberQuest_ScanToolTip()
	elseif (event == "QUEST_WATCH_UPDATE" and UberQuest_Config.addprogress) then
                 --DEFAULT_CHAT_FRAME:AddMessage("event="..event..", arg1="..arg1)
                 UberQuest_ToggleQuest(arg1,true)
	end
end

-- This is a function hook for scanning tool tips

function UberQuest_ContainerFrameItemButton_OnEnter(self)
	UberQuest_ScanToolTip()
	if (Orig_ContainerFrameItemButton_OnEnter) then
		Orig_ContainerFrameItemButton_OnEnter(self)
	end
end

function UberQuest_List_OnLoad(self)
		self.selectedButtonID = 2;
        -- ithilyn: new frame layout management in 2.1
        self:SetAttribute("UIPanelLayout-defined", true)
        self:SetAttribute("UIPanelLayout-enabled", true)
        self:SetAttribute("UIPanelLayout-area", "left")
        self:SetAttribute("UIPanelLayout-pushable", 997)
        self:SetAttribute("UIPanelLayout-whileDead", true)
end

--local old_ToggleQuestLog = ToggleQuestLog
function UberQuest_ListShowHide()
	HideUIPanel(QuestLogFrame);
	if (UberQuest_List:IsVisible()) then
		HideUIPanel(UberQuest_List)
		PlaySound("igQuestLogClose")
	else
		UberQuest_List_Title:SetText ("Uber Quest ("..UBERQUEST_VERSION..")")
		ShowUIPanel(UberQuest_List)
		UberQuest_List_Update()
		PlaySound("igQuestLogOpen")
		if (UberQuest_Details:IsVisible()) then
			UberQuest_Details_Update()
		end
	end
end

function UberQuest_Details_OnShow()
   if (UberQuest_LightHeadedSupport) then
      LightHeadedFrame:Show()
   end
 
end

function UberQuest_Details_OnHide()
   if (UberQuest_LightHeadedSupport) then
      LightHeadedFrame:Hide()
   end
end

function UberQuest_Minion_ShowHide()
	if (UberQuest_Minion:IsVisible() and UberQuest_Config[UberQuest_Player].selected) then
			UberQuest_Minion_Update()
		else
		UberQuest_Minion:Hide()
	end
end


-- ithilyn 2007/05/31
-- ripped from Blizzard's QuestLogFrame.lua
function UberQuest_QuestLogUpdateQuestCount(numQuests)
	UberQuest_QuestLogQuestCount:SetText(format(QUEST_LOG_COUNT_TEMPLATE, numQuests, MAX_QUESTLOG_QUESTS));
	local width = UberQuest_QuestLogQuestCount:GetWidth();
	local textHeight = 12;
	local hPadding = 15;
	local vPadding = 8;
	local dailyQuestsComplete = GetDailyQuestsCompleted();
	
	if ( dailyQuestsComplete > 0 ) then
		UberQuest_QuestLogDailyQuestCount:SetText(format(QUEST_LOG_DAILY_COUNT_TEMPLATE, dailyQuestsComplete, GetMaxDailyQuests()));
		UberQuest_QuestLogDailyQuestCount:Show();
		UberQuest_DailyQuestCountButton:Show();
		-- Use this width
		if ( UberQuest_QuestLogDailyQuestCount:GetWidth() > width ) then
			width = UberQuest_QuestLogDailyQuestCount:GetWidth();
		end
		UberQuest_QuestLogCount:SetHeight(textHeight*2+vPadding);
		UberQuest_QuestLogCount:SetPoint("TOPRIGHT", UberQuest_List, "TOPRIGHT", -44, -38);
	else
		UberQuest_QuestLogDailyQuestCount:Hide();
		UberQuest_DailyQuestCountButton:Hide();
		width = UberQuest_QuestLogQuestCount:GetWidth();
		UberQuest_QuestLogCount:SetHeight(textHeight+8);
		UberQuest_QuestLogCount:SetPoint("TOPRIGHT", UberQuest_List, "TOPRIGHT", -44, -41);
	end
	UberQuest_QuestLogCount:SetWidth(width+hPadding);
end

function UberQuest_List_Update()
        if (not UberQuest_Config) then
           DEFAULT_CHAT_FRAME:AddMessage("UberQuest not loaded yet, please wait a few seconds...")
           return
        end
	local i
	UberQuest_QuestTitles = {}
	if (UberQuest_Config.useminion) then
		UberQuest_List_SummonMinion:Show()
	else
		UberQuest_List_SummonMinion:Hide()
		UberQuest_Minion:Hide()
	end
	-- Copied muchly from QuestLog_Update(), Blizzard code, with updates for sexual prowess.
	local numEntries, numQuests = GetNumQuestLogEntries()
	if ( numEntries == 0 ) then
		--EmptyQuestLogFrame:Show()
		UberQuest_List_AbandonButton:Disable()
		UberQuest_List.hasTimer = nil
		UberQuest_List_ExpandButtonFrame:Hide()
	else
		--EmptyQuestLogFrame:Hide()
		UberQuest_List_AbandonButton:Enable()
		UberQuest_List_ExpandButtonFrame:Show()
		-- UberQuest_Details_Title:SetText ("Uber Quest ("..UBERQUEST_VERSION..")")
		-- UberQuest_Details:Show()
		-- UberQuest_Details_Update()
	end
	-- Update Quest Count
        -- ithilyn 2007/05/31
	--UberQuest_List_QuestCount:SetText(format(QUEST_LOG_COUNT_TEMPLATE, numQuests, MAX_QUESTLOG_QUESTS))
	--UberQuest_List_CountMiddle:SetWidth(UberQuest_List_QuestCount:GetWidth())
        UberQuest_QuestLogUpdateQuestCount(numQuests)

	-- ScrollFrame update
	FauxScrollFrame_Update(UberQuest_List_Scroll, numEntries, UBERQUEST_QUESTS_DISPLAYED, UBERQUEST_QUESTLINE_HEIGHT, nil, nil, nil, UberQuest_List_HighlightFrame, 293, 316 )

	if (numQuests and numQuests > 0) then
		local i = 1
                while true do
			local quest, level, questTag, suggestedGroup, isHeader, isCollapsed, isDaily = GetQuestLogTitle(i)
                        if (not quest) then
                           break
                        end
			if (not isHeader) then
				if (UberQuest_GotFullList and UberQuest_Config.addnewquests and not UberQuest_ActivityTracker[quest]) then
					UberQuest_Config[UberQuest_Player].selected[quest] = 1
				end
				if (not UberQuest_ActivityTracker[quest]) then
					UberQuest_ActivityTracker[quest] = {}
				end
			end
                        i = i + 1
		end
		if (UberQuest_ActivityTracker ~= {}) then
			UberQuest_GotFullList = true
		end
	end
	local numPartyMembers = GetNumPartyMembers()
	-- Update the quest listing
	UberQuest_List_HighlightFrame:Hide()
	for i=1, UBERQUEST_QUESTS_DISPLAYED, 1 do
		local questIndex = i + FauxScrollFrame_GetOffset(UberQuest_List_Scroll)
		local questLogTitle = getglobal("UberQuest_List_Title"..i)
		local questTitleTag = getglobal("UberQuest_List_Title"..i.."Tag")
		local questNormalText = getglobal("UberQuest_List_Title"..i.."NormalText")
		local questHighlightText = getglobal("UberQuest_List_Title"..i.."NormalText")
		local questDisabledText = getglobal("UberQuest_List_Title"..i.."NormalText")
		local questNumGroupMates = getglobal("UberQuest_List_Title"..i.."GroupMates")
		if ( questIndex <= numEntries ) then
			local questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily = GetQuestLogTitle(questIndex)
			local color
			questLogTitle.questID = questIndex
			if ( isHeader ) then
				if ( questLogTitleText ) then
					questLogTitle:SetText(questLogTitleText)
				else
					questLogTitle:SetText("")
				end
				
				if ( isCollapsed ) then
					questLogTitle:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-Up")
				else
					questLogTitle:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-Up") 
				end
				questNumGroupMates:SetText("")
				getglobal("UberQuest_List_Title"..i.."Highlight"):SetTexture("Interface\\Buttons\\UI-PlusButton-Hilight")
				getglobal("UberQuest_List_Title"..i.."_MinionSelect"):Hide()
			else
				UberQuest_QuestTitles[i] = questLogTitleText
				if (UberQuest_Config.useminion) then
					getglobal("UberQuest_List_Title"..i.."_MinionSelect"):Show()
					getglobal("UberQuest_List_Title"..i.."_MinionSelect"):SetChecked(UberQuest_Config[UberQuest_Player].selected[questLogTitleText])
				else
					getglobal("UberQuest_List_Title"..i.."_MinionSelect"):Hide()
				end
				
				if ( UberQuest_Config.showquestlevels == 1 ) then		
				if ( questTag == ELITE or questTag == GROUP ) then
					questLogTitle:SetText("  ["..level.."+] "..questLogTitleText)
				else									
			
					if ( questTag == RAID or questTag == "Schlachtzug" ) then
						questLogTitle:SetText("  ["..level.."R] "..questLogTitleText)
														
					else
						if ( questTag == "Dungeon" or questTag == "Donjon" or questTag == "Instanz" ) then
							questLogTitle:SetText("  ["..level.."D] "..questLogTitleText)
						else
							if ( questTag == "PvP" ) then
								questLogTitle:SetText("  ["..level.."P] "..questLogTitleText)
							elseif ( questTag == "Heroic" ) then
								questLogTitle:SetText("  ["..level.."H] "..questLogTitleText)
							else					
								questLogTitle:SetText("  ["..level.."] "..questLogTitleText)
							end
						end
					end
				end
				
			
		else
			questLogTitle:SetText("  "..questLogTitleText)
						
										
		end		
										
				questLogTitle:SetNormalTexture("")
				getglobal("UberQuest_List_Title"..i.."Highlight"):SetTexture("")
				local partyMembersOnQuest = 0
				for j=1, numPartyMembers do
					local isOnQuest = IsUnitOnQuest(questIndex, "party"..j)
					if ( isOnQuest and isOnQuest == 1 ) then
						partyMembersOnQuest = partyMembersOnQuest + 1
					end
				end
				if ( partyMembersOnQuest > 0 ) then
					questNumGroupMates:SetText("["..partyMembersOnQuest.."]")
				else
					questNumGroupMates:SetText("")
				end
			end
			-- Set the quest tag
                        -- ithilyn 2007/05/31
			if ( isComplete and isComplete < 0 ) then
				questTag = FAILED;
			elseif ( isComplete and isComplete > 0 ) then
				questTag = COMPLETE;
			elseif ( isDaily ) then
				if ( questTag ) then
					questTag = format(DAILY_QUEST_TAG_TEMPLATE, questTag);
				else
					questTag = DAILY;
				end
			end
			if ( questTag ) then
                                if (suggestedGroup > 0) then
                                        questTag = questTag..":"..suggestedGroup
                                end
				questTitleTag:SetText("("..questTag..")")
				-- Shrink text to accomdate quest tags without wrapping
				-- This is just wrong, so very very wrong.
				-- (Elite) is coming out at width 80
				if (questTag == "Elite" or questTag == "Raid" or questTag == "Fertig" or questTag == "PvP" or questTag == GROUP) then
					questNormalText:SetWidth(215)
				elseif (questTag == "Complete" or questTag == "Dungeon" or questTag == "Instanz") then
					questHighlightText:SetWidth(200)
					questDisabledText:SetWidth(200)
				elseif (questTag == "Schlachtzug") then
					questNormalText:SetWidth(205)
					questHighlightText:SetWidth(205)
					questDisabledText:SetWidth(205)
				else
					questNormalText:SetWidth(275 - 5 - questTitleTag:GetWidth())
					questHighlightText:SetWidth(275 - 5 - questTitleTag:GetWidth())
					questDisabledText:SetWidth(275 - 5 - questTitleTag:GetWidth())
				end
			else
				questTitleTag:SetText("")
				-- Reset to max text width
				questNormalText:SetWidth(275)
				questHighlightText:SetWidth(275)
				questDisabledText:SetWidth(275)
			end

			-- Color the quest title and highlight according to the difficulty level
			local playerLevel = UnitLevel("player")
			if ( isHeader ) then
				color = QuestDifficultyColor["header"]
			else
					color = GetDifficultyColor(level)
			end
			questTitleTag:SetTextColor(color.r, color.g, color.b);
			questLogTitle:SetNormalFontObject(color.font);
			questNumGroupMates:SetTextColor(color.r, color.g, color.b);
			questLogTitle.r = color.r
			questLogTitle.g = color.g
			questLogTitle.b = color.b
			questLogTitle:Show()

			-- Place the highlight and lock the highlight state
			if ( UberQuest_List.selectedButtonID and GetQuestLogSelection() == questIndex ) then
			UberQuest_List_HighlightFrame:SetPoint("TOPLEFT", "UberQuest_List_Title"..i, "TOPLEFT", 0, 0)
			UberQuest_List_HighlightFrame:Show()
				questTitleTag:SetTextColor(HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b)
				questLogTitle:LockHighlight()
			else
				questLogTitle:UnlockHighlight()
			end
		else
			questLogTitle:Hide()
		end
	end
		
	-- Set the expand/collapse all button texture
	local numHeaders = 0
	local notExpanded = 0
	-- Somewhat redundant loop, but cleaner than the alternatives
	for i=1, numEntries, 1 do
		local questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isDaily = GetQuestLogTitle(i)
		if ( questLogTitleText and isHeader ) then
			numHeaders = numHeaders + 1
			if ( isCollapsed ) then
				notExpanded = notExpanded + 1
			end
		end
	end
	-- If all headers are not expanded then show collapse button, otherwise show the expand button
	if ( notExpanded ~= numHeaders ) then
		UberQuest_List_ExpandButtonFrame_CollapseAllButton.collapsed = nil
		UberQuest_List_ExpandButtonFrame_CollapseAllButton:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-Up")
	else
		UberQuest_List_ExpandButtonFrame_CollapseAllButton.collapsed = 1
		UberQuest_List_ExpandButtonFrame_CollapseAllButton:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-Up")
	end

	-- Update Quest Count
        -- ithilyn 2007/05/31
	--UberQuest_List_QuestCount:SetText(format(QUEST_LOG_COUNT_TEMPLATE, numQuests, MAX_QUESTLOG_QUESTS))
	--UberQuest_List_CountMiddle:SetWidth(UberQuest_List_QuestCount:GetWidth())
        UberQuest_QuestLogUpdateQuestCount(numQuests)

	-- If no selection then set it to the first available quest
	if ( GetQuestLogSelection() == 0 ) then
		UberQuest_SetFirstValidSelection()
	end

	-- Determine whether the selected quest is pushable or not
	if ( numEntries == 0 ) then
		UberQuest_List_ShareButton:Disable()
	elseif ( GetQuestLogPushable() and GetNumPartyMembers() > 0 ) then
		UberQuest_List_ShareButton:Enable()
	else
		UberQuest_List_ShareButton:Disable()
	end
end


function UberQuest_List_CollapseAll_OnClick(button)

	local doCollapse
	if(UberQuest_List_ExpandButtonFrame_CollapseAllButton.collapsed) then
		doCollapse = false
	else
		doCollapse = true
	end
	i = 1
	while (true) do
		local numEntries, numQuests = GetNumQuestLogEntries()
		--DEFAULT_CHAT_FRAME:AddMessage("numEntries="..numEntries..", numQuests="..numQuests)
		if (i > numEntries) then break end
		local questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isDaily = GetQuestLogTitle(i)
		if ( questLogTitleText and isHeader ) then
			if (doCollapse and not isCollapsed) then
				UberQuest_List_SetSelection(i)
			elseif (not doCollapse and isCollapsed) then
				UberQuest_List_SetSelection(i)
			end
		end
		i = i + 1
	end
end

function UberQuest_DetailsShowHide()
	if (UberQuest_Details:IsVisible()) then
		UberQuest_Details:Hide()
	else
		UberQuest_Details_Title:SetText ("Uber Quest ("..UBERQUEST_VERSION..")")
		UberQuest_Details:Show()
		UberQuest_Details_Update()
	end
end

function UberQuest_ConfigShowHide()
	if (UberQuest_ConfigFrame:IsVisible()) then
		UberQuest_ConfigFrame:Hide()
	else
		UberQuest_ConfigFrame:Show()
		UberQuest_Config_Update()
	end
end

function UberQuest_Config_Update()
	UberQuest_ConfigFrame_ShowQuestLevels:SetChecked(UberQuest_Config.showquestlevels)
	UberQuest_ConfigFrame_UseMinion:SetChecked(UberQuest_Config.useminion)
	UberQuest_ConfigFrame_LockMinion:SetChecked(UberQuest_Config[UberQuest_Player].lockminion)
	UberQuest_ConfigFrame_MinionAddNew:SetChecked(UberQuest_Config.addnewquests)
	UberQuest_ConfigFrame_MinionAddProg:SetChecked(UberQuest_Config.addprogress)
	UberQuest_ConfigFrame_ColorizeObjective:SetChecked(UberQuest_Config.colorizeobjectives)
	UberQuest_ConfigFrame_ExpireObjective:SetChecked(UberQuest_Config.expireobjectives) -- EMERALD
	UberQuest_ConfigFrame_ExpireQuest:SetChecked(UberQuest_Config.expirequests) -- EMERALD
	UberQuest_ConfigFrame_ToggleMinionText:SetChecked(UberQuest_Config.hidetext) -- D.I.
	UberQuest_ConfigFrame_CompletionAlert:SetChecked(UberQuest_Config.completionAlert) -- ithilyn
	UberQuest_ConfigFrame_ShowZone:SetChecked(UberQuest_Config.showZone) -- Oggy
	UberQuest_ConfigFrame_ActiveMinion:SetChecked(UberQuest_Config.activeMinion) -- Oggy
	UberQuest_ConfigFrame_ToolTips:SetChecked(UberQuest_Config.showTip) -- Oggy

	if (UberQuest_Config.useminion) then
		UberQuest_ConfigFrame_LockMinion:Enable()
		UberQuest_ConfigFrame_MinionAddNew:Enable()
		UberQuest_ConfigFrame_ColorizeObjective:Enable()
		UberQuest_ConfigFrame_ExpireObjective:Enable() -- EMERALD
		UberQuest_ConfigFrame_ExpireQuest:Enable() -- EMERALD
		UberQuest_ConfigFrame_CompletionAlert:Enable()
		UberQuest_ConfigFrame_ShowZone:Enable()  -- Oggy
		UberQuest_ConfigFrame_ActiveMinion:Enable()  -- Oggy
	else
		UberQuest_ConfigFrame_LockMinion:Disable()
		UberQuest_ConfigFrame_MinionAddNew:Disable()
		UberQuest_ConfigFrame_ColorizeObjective:Disable()
		UberQuest_ConfigFrame_ExpireObjective:Disable() -- EMERALD
		UberQuest_ConfigFrame_ExpireQuest:Disable() -- EMERALD
		UberQuest_ConfigFrame_CompletionAlert:Disable()
		UberQuest_ConfigFrame_ShowZone:Disable()  -- Oggy
		UberQuest_ConfigFrame_ActiveMinion:Disable()  -- Oggy
	end

	-- Active minion does not work when minion is locked -- Oggy
	--if (UberQuest_Config[UberQuest_Player].lockminion) then
	--	UberQuest_ConfigFrame_ActiveMinion:Disable()
	--end
	
	UberMinion_Scale_Update()


	if (UberQuest_Config.color and UberQuest_Config.color.r and UberQuest_Config.color.g and UberQuest_Config.color.b and UberQuest_Config.color.opacity) then
		UberQuest_Minion_ColorPicker = { r = UberQuest_Config.color.r, 
						 g = UberQuest_Config.color.g, 
						 b = UberQuest_Config.color.b } 
		UberQuest_ConfigFrame_BGColorSwatchBg:SetVertexColor(UberQuest_Config.color.r, 
								UberQuest_Config.color.g, 
								UberQuest_Config.color.b)
	else
		UberQuest_Minion_ColorPicker = { r = TOOLTIP_DEFAULT_BACKGROUND_COLOR.r, 
						 g = TOOLTIP_DEFAULT_BACKGROUND_COLOR.g, 
						 b = TOOLTIP_DEFAULT_BACKGROUND_COLOR.b } 
		UberQuest_ConfigFrame_BGColorSwatchBg:SetVertexColor(TOOLTIP_DEFAULT_BACKGROUND_COLOR.r, 
								TOOLTIP_DEFAULT_BACKGROUND_COLOR.g, 
								TOOLTIP_DEFAULT_BACKGROUND_COLOR.b)
	end
end

function UberQuest_Minion_OnOff(val)
	if (val) then
	else
		if (UberQuest_Minion:IsVisible()) then
			UberQuest_MinionShowHide()
		end
	end
end

function UberQuest_MinionSelect_OnClick(button)
	if (UberQuest_QuestTitles[this:GetParent():GetID()]) then
		if (this:GetChecked()) then
			--DEFAULT_CHAT_FRAME:AddMessage("Checking "..UberQuest_QuestTitles[this:GetParent():GetID()])
			UberQuest_Config[UberQuest_Player].selected[UberQuest_QuestTitles[this:GetParent():GetID()]] = 1
		else
			--DEFAULT_CHAT_FRAME:AddMessage("Unchecking")
			UberQuest_Config[UberQuest_Player].selected[UberQuest_QuestTitles[this:GetParent():GetID()]] = nil
		end
		if (UberQuest_Minion:IsVisible()) then
			UberQuest_Minion_Update()
		end
	end
end


function UberQuest_MinionShowHide()
	if (UberQuest_Config and UberQuest_Player and UberQuest_Config[UberQuest_Player]) then
		if (UberQuest_Minion:IsVisible()) then
			UberQuest_Minion:Hide()
			UberQuest_List_SummonMinion:SetText(UBERQUEST_SUMMONMINION)
			UberQuest_Config[UberQuest_Player].minionvisible = nil
		else
			--DEFAULT_CHAT_FRAME:AddMessage("Showing Minion")
			UberQuest_Minion:Show()
			UberQuest_List_SummonMinion:SetText(UBERQUEST_DISMISSMINION)
			UberQuest_Minion_Update()
			UberQuest_Config[UberQuest_Player].minionvisible = 1
		end
	end
end

function UberQuest_Minion_Update()

	local applytext = ""
	local indenttext = ""
	local questlist = {}
	local i = 1
	local j
	local realheight = 0
	local realwidth = 0
	local whichLine = 1
	local doneZone = false
	local zone = ""
	if (UberQuest_Config and UberQuest_Player and UberQuest_Config[UberQuest_Player] and UberQuest_Config[UberQuest_Player].selected and UberQuest_Config[UberQuest_Player].selected ~= {}) then

		UberQuest_Minion_ClearLines()
		local category = nil
		local questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily = GetQuestLogTitle(i)
		while (questLogTitleText) do
			applytext = ""
			--DEFAULT_CHAT_FRAME:AddMessage ("Current quest is "..questLogTitleText)
			if (isHeader and UberQuest_Config.showZone ~= nil) then
				category = questLogTitleText
				zone = questLogTitleText
				doneZone = false
			elseif (UberQuest_Config[UberQuest_Player].selected[questLogTitleText]) then
				questlist[questLogTitleText] = i
				UberQuests_ThereAreQuests = 1

				if (not isComplete or (isComplete and not UberQuest_Config.expirequests)) then
					if (not doneZone and zone ~= "" and UberQuest_Config.showZone ~= nil) then
						whichLine,realheight,realwidth = UberQuest_Minion_ApplyText(zone,whichLine,0,realheight,realwidth)
						indenttext = "    "
						doneZone = true
					end
				end
				

				applytext = FormatQuestTitle(questLogTitleText,level,questTag)
				--DEFAULT_CHAT_FRAME:AddMessage ("Current quest is "..applytext)
				
				if (isComplete) then
					if (not UberQuest_Config.expirequests) then
						color = ConvertColorFormat(QuestDifficultyColor["header"])
						applytext = applytext.." |cff"..color.."("..UBERQUEST_QCOMPLETE..")|r"
						whichLine,realheight,realwidth = UberQuest_Minion_ApplyText(indenttext..applytext,whichLine,i,realheight,realwidth)

					end
				else
					-- Display the quest
					whichLine,realheight,realwidth = UberQuest_Minion_ApplyText(indenttext..applytext,whichLine,i,realheight,realwidth)

					SelectQuestLogEntry(i)
					for j = 1, GetNumQuestLeaderBoards(), 1 do
						applytext=""
						local text, typ, finished = GetQuestLogLeaderBoard(j)
						if ( not text or strlen(text) == 0 ) then
							text = typ
						end
						
						if (finished and not UberQuest_Config.expireobjectives) then
							color = ConvertColorFormat(QuestDifficultyColor["header"])
							applytext = "   |cff"..color..text.." ("..UBERQUEST_QCOMPLETE..")|r"
						elseif (not finished) then
							local item, now, max
							color = "ffffff"
							for item, now, max in string.gmatch(text,"([^:]+): (%d+)/(%d+)$") do
								if (item and now and max) then
									if (UberQuest_Config.colorizeobjectives) then
										color = DifficultyColor(now,max)
									else
										color = "ffffff"
									end

								end
							end
							applytext = "   |cff"..color..text.."|r"
						end
						if (applytext ~= "") then
							whichLine,realheight,realwidth = UberQuest_Minion_ApplyText(indenttext..applytext,whichLine,i,realheight,realwidth)
						end
					end
				end
			end
			i = i + 1
			questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily = GetQuestLogTitle(i)
		end
		if (realheight == 0) then
			if (UberQuest_Config.hidetext) then
				whichLine,realheight,realwidth = UberQuest_Minion_ApplyText("",whichLine,1,realheight,realwidth)
				--UberQuest_Minion_Text:SetText("")
			else
				--UberQuest_Minion_Text:SetText(UBERQUEST_MINION_NOQUESTS)
				whichLine,realheight,realwidth = UberQuest_Minion_ApplyText(UBERQUEST_MINION_NOQUESTS,whichLine,1,realheight,realwidth)
			end
		
		end
		if (UberQuests_ThereAreQuests) then
			for i in pairs(UberQuest_Config[UberQuest_Player].selected) do

				if (not questlist[i]) then
					UberQuest_Config[UberQuest_Player].selected[i] = nil
					UberQuest_ActivityTracker[i] = nil
				end
			end
		end
	else
		if (UberQuest_Config.hidetext) then
			UberQuest_Minion_Text:SetText("")
		else
			UberQuest_Minion_Text:SetText(UBERQUEST_MINION_NOQUESTS)
		end
	end
	if (UberQuest_SelectedQuest) then
		SelectQuestLogEntry(UberQuest_SelectedQuest)
	end
	
	realwidth = realwidth + 25
	realheight = realheight + 25
	if (realwidth < 100) then realwidth = 100 end
	if (realheight < 30) then realheight = 30 end

	if (UberQuest_MinionSetOnce) then
		-- Running this before the Width and Height are set at least once always 
		-- screws up the corner locking.
		UberQuest_Minion_LockCornerForGrowth()
	end
	UberQuest_MinionSetOnce = 1
	UberQuest_Minion:SetWidth(realwidth)
	UberQuest_Minion:SetHeight(realheight)

	
	
	--local width = UberQuest_Minion_Text:GetWidth() + 25
	--local height = UberQuest_Minion_Text:GetHeight() + 25
	--if (width < 100) then width = 100 end
	--if (height < 30) then height = 30 end
	--if (UberQuest_MinionSetOnce) then
	--	-- Running this before the Width and Height are set at least once always 
	--	-- screws up the corner locking.
	--	UberQuest_Minion_LockCornerForGrowth()
	--end
	--UberQuest_MinionSetOnce = 1
	--UberQuest_Minion:SetWidth(width)
	--UberQuest_Minion:SetHeight(height + realheight)
end



function FormatQuestTitle(questLogTitleText,level,questTag)
	local color = ConvertColorFormat(GetDifficultyColor(level))
	local text = "|cff"..color
	if (UberQuest_Config.showquestlevels ==1) then
	
	        if ( questTag == ELITE or questTag == GROUP ) then
			text = text.."["..level.."+] "
		else									
	
			if ( questTag == RAID or questTag == "Schlachtzug") then
				text = text.."["..level.."R] "
							
			else
				if ( questTag == "Dungeon" or questTag == "Donjon" or questTag == "Instanz") then
					text = text.."["..level.."D] "
				else	
					if ( questTag == "PvP") then
						text = text.."["..level.."P] "
					elseif ( questTag == "Heroic") then
						text = text.."["..level.."H] "
					else
						text = text.."["..level.."] "
					end
				end
			end
		end

	end
	text = text..questLogTitleText.."|r"
	return text
end

function ConvertColorFormat(color) 
	local function dec2hex(decnum)
		if (decnum == 0) then return "00" end
		local hexnum=""
		local tempval
		decnum = 255*decnum
		if ((decnum-math.floor(decnum)) > 0) then
			decnum = decnum + 1
		end
		decnum = math.floor(decnum)
		while (decnum ~= 0) do
			tempval = math.fmod(decnum,16)
			if (tempval > 9) then
				tempval = string.char(tempval + 55)
			end
			hexnum = tempval..hexnum
			decnum = math.floor(decnum / 16) 
			if (decnum < 16) then
				if (decnum > 9) then
					decnum = string.char(decnum + 55)
				end
				hexnum = decnum..hexnum 
				decnum = 0 
			end
		end
		return hexnum
	end
	return (dec2hex(color.r)..dec2hex(color.g)..dec2hex(color.b))
end


function DifficultyColor(now,max)
	local startrange = QuestDifficultyColor["impossible"]
	local midrange = QuestDifficultyColor["difficult"]
	local endrange = QuestDifficultyColor["standard"]
	now = tonumber(now) 
	max = tonumber(max)
	if (not now or now == 0 or now > max) then
		return ConvertColorFormat(startrange)
	elseif (now == (max / 2)) then
		return ConvertColorFormat(midrange)
	elseif (now == max) then
		return ConvertColorFormat(endrange)
	elseif (now <= (max / 2)) then
		local color = {}
		local percent = now / max
		color.r = startrange.r
		color.g = startrange.g + ((midrange.g - startrange.g) * percent)
		color.b = startrange.b - ((startrange.b - midrange.b) * percent)
		return ConvertColorFormat(color)
	else 
		local color = {}
		local percent = now / max
		color.r = midrange.r - ((midrange.r - endrange.r) * percent)
		color.g = midrange.g - ((midrange.g - endrange.g) * percent)
		color.b = midrange.b + ((endrange.b - midrange.b) * percent)
		return ConvertColorFormat(color)
	end
end


function UberQuest_Minion_ApplyText(text,lineNum,quest,currHeight,currWidth)
	local newWidth
	
	--DEFAULT_CHAT_FRAME:AddMessage("Add "..text.." to line "..lineNum..", height "..currHeight..", width "..currWidth);
	local line = getglobal("UberQuest_Minion_Line"..lineNum)
	line:SetText(text)
	line.quest = quest
	if (currWidth > line:GetWidth()) then
		newWidth = currWidth
	else
		newWidth = line:GetWidth()
	end
	return lineNum + 1,currHeight + line:GetHeight(),newWidth
end

function UberQuest_Minion_ClearLines()
	local i
	for i = 1,UBERQUEST_NUM_MINION_LINES,1 do
		local line = getglobal("UberQuest_Minion_Line"..i)
		line.quest = 0
		line:SetText("")
	end
end

function UberQuest_Minion_OnUpdate()
	if (not UberQuest_Config.activeMinion) then return end
	if (IsAltKeyDown()) then
		local good,quest = UberQuest_Minion_CheckMouse(self)
		if (good) then
			SetCursor("CAST_CURSOR")
		else
			SetCursor(nil)
			--DEFAULT_CHAT_FRAME:AddMessage("ResetCursor");
		end
	elseif (MouseIsOver(this)) then
		SetCursor(nil)
	end
end


function UberQuest_Minion_OnClick()
	if (not UberQuest_Config.activeMinion) then return end
	if (IsAltKeyDown()) then
		local good,quest = UberQuest_Minion_CheckMouse(self)
		if (good) then
			local questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily = GetQuestLogTitle(quest)
			--DEFAULT_CHAT_FRAME:AddMessage("CLICK!! Quest is "..questLogTitleText);
			if(not UberQuest_List:IsVisible()) then
				UberQuest_ListShowHide()
			end
			UberQuest_List_SetSelection(quest)
			UberQuest_List_Update()
			UberQuest_Details_Update()
		        if (UberQuest_LightHeadedSupport) then
		           --LightHeaded:QuestLogTitleButton_OnClick()
		           LightHeaded:SelectQuestLogEntry()
		        end
		end
	end
end

function UberQuest_Minion_CheckMouse()
	if (MouseIsOver(this)) then
		local x,y = GetMouseCoords(this)

		for i=1,UBERQUEST_NUM_MINION_LINES,1 do
			local line = getglobal("UberQuest_Minion_Line"..i)
			if (line == nil) then return end
			local l = line:GetLeft()
			local r = line:GetRight()
			local t = line:GetTop()
			local b = line:GetBottom()
			
			if ( x <= r and x >= l and y <= t and y >= b ) then
				if (line.quest ~= 0 ) then
					return true,line.quest
				end
			end
		end
	end
	return false,0
end


function GetMouseCoords(frame)
	local x, y = GetCursorPosition();
	local s = frame:GetEffectiveScale()
	x = x/s
	y = y/s
	return x,y
end

function UberQuest_Minion_LockCornerForGrowth()
	local Left = UberQuest_Minion:GetLeft()
	local Right = UberQuest_Minion:GetRight()
	local Top = UberQuest_Minion:GetTop()
	local Bottom = UberQuest_Minion:GetBottom()
	local lock
	local pointone
	local pointtwo
	local TOPBOTTOM_MEDIAN = 384
	local LEFTRIGHT_MEDIAN = 512
	if (Left and Right and Top and Bottom) then
		if (Bottom < TOPBOTTOM_MEDIAN and Top > TOPBOTTOM_MEDIAN) then
			local topcross = Top - TOPBOTTOM_MEDIAN
			local bottomcross = TOPBOTTOM_MEDIAN - Bottom
			if (bottomcross > topcross) then
				lock = "BOTTOM"
				pointtwo = Bottom
			else
				lock = "TOP"
				pointtwo = Top
			end
		elseif (Top > TOPBOTTOM_MEDIAN) then
			lock = "TOP"
			pointtwo = Top
		elseif (Bottom < TOPBOTTOM_MEDIAN) then
			lock = "BOTTOM"
			pointtwo = Bottom
		end
		if (Left < LEFTRIGHT_MEDIAN and Right > LEFTRIGHT_MEDIAN) then
			-- Minion crossed the LEFT/RIGHT median
			local leftcross = LEFTRIGHT_MEDIAN - Left
			local rightcross = Right - LEFTRIGHT_MEDIAN
			if (rightcross > leftcross) then
				lock = lock.."RIGHT"
				pointone = Right
			else
				lock = lock.."LEFT"
				pointone = Left
			end
		elseif (Left < LEFTRIGHT_MEDIAN) then
			lock = lock.."LEFT"
			pointone = Left
		elseif (Right > LEFTRIGHT_MEDIAN) then
			lock = lock.."RIGHT"
			pointone = Right
		end
		if (lock and lock ~= "" and pointone and pointtwo) then
			UberQuest_Minion:ClearAllPoints()
			UberQuest_Minion:SetPoint(lock,"UIParent","BOTTOMLEFT",pointone,pointtwo)
			UberQuest_Config[UberQuest_Player].lock = {}
			UberQuest_Config[UberQuest_Player].lock.corner = lock
			UberQuest_Config[UberQuest_Player].lock.pointone = pointone
			UberQuest_Config[UberQuest_Player].lock.pointtwo = pointtwo
		elseif (UberQuests_ThereAreQuests and
			UberQuest_Config[UberQuest_Player].lock and
			UberQuest_Config[UberQuest_Player].lock.corner and
			UberQuest_Config[UberQuest_Player].lock.pointone and
			UberQuest_Config[UberQuest_Player].lock.pointtwo) then
			UberQuest_Minion:ClearAllPoints()
			UberQuest_Minion:SetPoint(UberQuest_Config[UberQuest_Player].lock.corner,"UIParent","BOTTOMLEFT",UberQuest_Config[UberQuest_Player].lock.pointone,UberQuest_Config[UberQuest_Player].lock.pointtwo)
		end
	end
end

function UberQuest_TitleButton_OnClick(self, button)
	if ( button == "LeftButton" ) then
		if ( IsShiftKeyDown() and ChatFrameEditBox:IsVisible() ) then
			--ChatFrameEditBox:Insert(this:GetText())
			ChatFrameEditBox:Insert(GetQuestLink(self.questID))
		end
		UberQuest_List_SetSelection(self:GetID() + FauxScrollFrame_GetOffset(UberQuest_List_Scroll))
		UberQuest_List_Update()
	end
        if (UberQuest_LightHeadedSupport) then
           --LightHeaded:QuestLogTitleButton_OnClick()
           LightHeaded:SelectQuestLogEntry()
        end
end

function UberQuest_Minion_ColorPick()
	ColorPickerFrame.func = UberQuest_Minion_SetColor
	ColorPickerFrame.hasOpacity = 1
	ColorPickerFrame.opacityFunc = UberQuest_Minion_SetOpacity
	ColorPickerFrame.cancelFunc = UberQuest_Minion_Cancel
	ColorPickerFrame:SetFrameStrata("TOOLTIP")
	ColorPickerFrame:Raise()
	if (UberQuest_Config.color and UberQuest_Config.color.r and UberQuest_Config.color.g and UberQuest_Config.color.b and UberQuest_Config.color.opacity) then
		ColorPickerFrame:SetColorRGB(	UberQuest_Config.color.r,
						UberQuest_Config.color.g,
						UberQuest_Config.color.b)
		ColorPickerFrame.opacity = UberQuest_Config.color.opacity
		ColorPickerFrame.previousValues = {r=UberQuest_Config.color.r, g=UberQuest_Config.color.g, b=UberQuest_Config.color.b, opacity=UberQuest_Config.color.opacity}
	else
		ColorPickerFrame:SetColorRGB(TOOLTIP_DEFAULT_BACKGROUND_COLOR.r,TOOLTIP_DEFAULT_BACKGROUND_COLOR.g,TOOLTIP_DEFAULT_BACKGROUND_COLOR.b)
		ColorPickerFrame.previousValues = {r=TOOLTIP_DEFAULT_BACKGROUND_COLOR.r, g=TOOLTIP_DEFAULT_BACKGROUND_COLOR.g, b=TOOLTIP_DEFAULT_BACKGROUND_COLOR.b, opacity=0}
		ColorPickerFrame.opacity = 0
	end
	ShowUIPanel(ColorPickerFrame)
end

function UberQuest_Minion_SetColor()
	local r,g,b = ColorPickerFrame:GetColorRGB()
	UberQuest_MinionBackdrop:SetBackdropColor(r, g, b)
	if (not UberQuest_Config.color) then
		UberQuest_Config.color = {}
	end
	UberQuest_Config.color.r = r
	UberQuest_Config.color.g = g
	UberQuest_Config.color.b = b
	UberQuest_Config_Update()
end

function UberQuest_Minion_SetOpacity()
	local alpha = 1.0 - OpacitySliderFrame:GetValue()
	UberQuest_MinionBackdrop:SetAlpha(alpha)
	if (not UberQuest_Config.color) then
		UberQuest_Config.color = {}
	end
	UberQuest_Config.color.opacity = OpacitySliderFrame:GetValue()
end

function UberQuest_Minion_Cancel(previousValues)
	if (not UberQuest_Config.color) then
		UberQuest_Config.color = {}
	end
	if (previousValues.r and previousValues.g and previousValues.b) then
		UberQuest_MinionBackdrop:SetBackdropColor(previousValues.r, previousValues.g, previousValues.b)
		UberQuest_Config.color.r = previousValues.r
		UberQuest_Config.color.g = previousValues.g
		UberQuest_Config.color.b = previousValues.b
	end
	if (previousValues.opacity) then
		local alpha = 1.0 - previousValues.opacity
		UberQuest_MinionBackdrop:SetAlpha(alpha)
		UberQuest_Config.color.opacity = previousValues.opacity
	end
	UberQuest_Config_Update()
end

function UberMinion_Scale_Update()
	local scale = UberMinionScale:GetValue() / 100
	UberQuest_Minion:SetScale(UIParent:GetScale() * scale)
	UberQuest_Config[UberQuest_Player].scale = scale
	UberQuest_Minion_Update()
end


-- Tool Tip Scanning


function UberQuest_ScanToolTip()
	if (not UberQuest_Config.showTip) then return end
	--DEFAULT_CHAT_FRAME:AddMessage("In ScanToolTip")
	if ( GameTooltip ~= nil and getglobal('GameTooltipTextLeft1'):IsVisible() and getglobal('GameTooltipTextLeft1'):GetText() ~= nil ) then
		UberQuest_ScanTooltipItem(getglobal('GameTooltipTextLeft1'):GetText())
	end
end

function UberQuest_ScanTooltipItem(queryString)
	
	local questID
	local numEntries, numQuests = GetNumQuestLogEntries();
	local numObjectives, questObjectives, questDescription;
	local found = false;
	local text, typ, finished;
	local x = nil;
	local item, now, max, color,toolTip, objText, found
	local tipModified

	if (not queryString) then return end
	
	queryString = RemoveEscSequence(queryString)
	
	-- We'll occasionally get zero-length strings or other strange things, so just ignore
	-- any string with less than, say, 4 characters
	
	if (strlen(queryString) < 4) then return end

	--DEFAULT_CHAT_FRAME:AddMessage("Scanning "..numEntries.." quests for >>"..queryString.."<< (length="..strlen(queryString)..")")
	
	-- loop through all quests
	for questID = 1, numEntries, 1 do
		local questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily = GetQuestLogTitle(questID)
		x = nil;
		
		if (not isHeader) then
			--SelectQuestLogEntry(questID);
			if(questLogTitleText) then				
				numObjectives = GetNumQuestLeaderBoards(questID);
				found = false
				if(numObjectives > 0) then	
					--DEFAULT_CHAT_FRAME:AddMessage("On quest "..questLogTitleText.." ("..questID.." of "..numEntries..")")
					-- loop through all objectives
					for objID = 1, numObjectives, 1 do
						text, typ, finished = GetQuestLogLeaderBoard(objID,questID);
						if(not text or strlen(text) == 0) then
							text = typ;
						end
						text = RemoveEscSequence(text)
						--DEFAULT_CHAT_FRAME:AddMessage("Searching for "..queryString.." in "..text)
						
						x = string.find(text, queryString);
						
						if (x ~= nil) then
							found = true
							break
						end
						
					end -- loop through all objectives
				end	
				if (found) then
					--DEFAULT_CHAT_FRAME:AddMessage("Found "..queryString.." in "..text)
					objText=""
					if (finished) then
						objText = "|cffffffff("..UBERQUEST_QCOMPLETE..")|r"
					else
						for item, now, max in string.gmatch(text,"([^:]+): (%d+)/(%d+)$") do
							if (item and now and max) then
								if (UberQuest_Config.colorizeobjectives) then
									color = DifficultyColor(now,max)
								else
									color = "ffffff"
								end
								objText = "|cff"..color.."("..now.."/"..max..")|r"
								break
							end
						end
					end
					
					-- Properly colorize and add quest levels, if configured.  Add the
					-- objective indicator
					
					toolTip = FormatQuestTitle(questLogTitleText,level,questTag).." "..objText
					
					-- If it's the first quest we're modifying, start it with a blank
					-- line and then the intro text.  Also, don't wrap quest lines, since
					-- it can make the quest line look ugly
					if (not tipModified) then 
						GameTooltip:AddLine(" ", 1, 1, 1, 0)
						GameTooltip:AddLine(UBERQUEST_QUEST_ITEM, 1, 1, 1, 0) 
						tipModified = true
					end
					GameTooltip:AddLine(toolTip, 1, 1, 1, 0);	
				end
			end
		end
		
	end -- loop through all quests
	
	-- If we've modified the tip, show it.  This will automatically
	-- readjust the height and width
	if (tipModified) then
		GameTooltip:Show()
	end
	
end

-- Remove any escape sequences from the string.  In addition,
-- square brackets seem to give difficulty to string pattern
-- matches, so remove them too.
-- Remove dashes (-) because they also give .find problems
-- Finally, trim any spaces and return the cleaned-up string.

-- I'm sure this is a total LUA noob way of doing it,
-- but I'm not an expert on patterns

function RemoveEscSequence(itemString)
	local newQuery = string.gsub(itemString,"\124c%x+","")
	newQuery = string.gsub(newQuery,"\124H(.+)","")
	newQuery = string.gsub(newQuery,"\124h%[.+%]","")
	newQuery = string.gsub(newQuery,"\124r","")
	newQuery = string.gsub(newQuery,"%[+","")
	newQuery = string.gsub(newQuery,"%]+","")
	newQuery = string.gsub(newQuery,"%-+","")
	return strtrim(newQuery)
end



function QuestLogTitleButton_OnEnter(self)
		-- Set highlight
	getglobal(self:GetName().."Tag"):SetTextColor(HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b)

		-- Set group info tooltip
	QuestLog_UpdatePartyInfoTooltip(self)
end


function QuestLog_UpdatePartyInfoTooltip(self)
	local index = self:GetID() + FauxScrollFrame_GetOffset(UberQuest_List_Scroll)
	local numPartyMembers = GetNumPartyMembers()
		if ( numPartyMembers == 0 or isHeader ) then
			return
		end
	GameTooltip_SetDefaultAnchor(GameTooltip, self)

	local questLogTitleText = GetQuestLogTitle(index)
	GameTooltip:SetText(questLogTitleText)

	local isOnQuest, unitName, partyMemberOnQuest
		for i=1, numPartyMembers do
			isOnQuest = IsUnitOnQuest( index, "party"..i)
			unitName = UnitName("party"..i)
				if ( isOnQuest and isOnQuest == 1 ) then
					if ( not partyMemberOnQuest ) then
						GameTooltip:AddLine(HIGHLIGHT_FONT_COLOR_CODE..PARTY_QUEST_STATUS_ON..FONT_COLOR_CODE_CLOSE)
						partyMemberOnQuest = 1
					end
					GameTooltip:AddLine(LIGHTYELLOW_FONT_COLOR_CODE..unitName..FONT_COLOR_CODE_CLOSE)
				end
		end
	if ( not partyMemberOnQuest ) then
		GameTooltip:AddLine(HIGHLIGHT_FONT_COLOR_CODE..PARTY_QUEST_STATUS_NONE..FONT_COLOR_CODE_CLOSE)
	end
	GameTooltip:Show()
end

-- inspired by EQL3.  thanks.
function CompletedQuestAlert()
   local currentQuests = {}
   local i = 1
   while true do
      local quest, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily = GetQuestLogTitle(i)
      if (not quest) then
         break
      end
      if (not isHeader) then
         currentQuests[quest] = true
         if (isComplete and not UberQuest_Config[UberQuest_Player].alerted[quest]) then
            UberQuest_Config[UberQuest_Player].alerted[quest] = true
            if (UberQuest_Config.completionAlert) then
               UIErrorsFrame:AddMessage(quest.." Completed!", 1.0, 0.8, 0.0, 1.0, UIERRORS_HOLD_TIME)
               PlaySound("GnomeExploration")
            end
         end
      end
      i = i + 1
   end

   -- clean up
   for quest in pairs(UberQuest_Config[UberQuest_Player].alerted) do
      if (not currentQuests[quest]) then
         UberQuest_Config[UberQuest_Player].alerted[quest] = nil
      end
   end
end

function UberQuest_ReattachLH()
	if UberQuest_LightHeadedSupport then
		 LightHeaded:AttachFrame()
		 LightHeaded:DetachFrame()
		 LightHeadedFrame:ClearAllPoints()
		 LightHeadedFrame:SetParent(UIParent)
		 LightHeadedFrame:SetHeight(424)
		 LightHeadedFrame:SetPoint("LEFT", UberQuest_Details, "RIGHT", -35, 24)
		 --LightHeadedFrame:SetPoint("TOPLEFT", UberQuest_List,"TOPRIGHT")
		 LightHeadedFrame:SetFrameStrata("HIGH")
		 LightHeadedFrame:Show()
		 --LightHeaded:LoadQIDData(nil)
	 end
end
